package com.kkb.mybatis.config;

import org.dom4j.Element;




/**
 * User: zsl
 * Date: 2019/10/1214:19
 * Description:
 */
public class XMLStatementPaser {
    private  Configuration configuration;

    public XMLStatementPaser(Configuration configuration) {
        this.configuration = configuration;
    }


    public void parseStatement(Element selectElement,String nameSpace) {
        String id = selectElement.attributeValue("id");
        String parameterType = selectElement.attributeValue("parameterType");
        Class<?> parameterTypeClass = resolveClass(parameterType);

        String resultType = selectElement.attributeValue("resultType");
        Class<?> resultTypeClass = resolveClass(resultType);

        String statementType = selectElement.attributeValue("statementType");
        statementType = statementType == null || statementType.equals("") ? "parement" : statementType;
        //SqlSource 就是封装了SQL语句
        //此处封装了sql没有进行处理,什么进行处理呢
        //处理时机就在 sqlsession 执行的时候
        //select  * from user where id = #{id}
        SqlSource sqlSource = createSqlSource(selectElement);
        String statementId = nameSpace + "." + id;
        //参数很多,有可能出错
        //使用构建者模式
        MappedStatement mappedStatement = new MappedStatement(statementId,parameterTypeClass,resultTypeClass,statementType,sqlSource);
        configuration.setMappedStatements(statementId,mappedStatement);
    }

    /**
     * 开始解析 select 里边的内容
     * 创建 sqlSource ,对select中的crud标签中的sql脚本进行处理,
     * @param selectElement
     * @return
     */
    private SqlSource createSqlSource(Element selectElement) {
        XMLScriptPaser xmlScriptPaser = new XMLScriptPaser(configuration);
        SqlSource sqlSource = xmlScriptPaser.parseScriptNode(selectElement);
        return sqlSource;
    }

    private Class<?> resolveClass(String parameterType) {
        try {
            return Class.forName(parameterType);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
